/**
 * @description  审批
 * @author zhangxinyue
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input } from 'antd';
import { FirstHeaderC, NoQueryC, PrimaryC, TableC } from '../../../comps';
import config from '../const.js';
import ApprovalHistory from '../approvalHistory';

const { TextArea } = Input;
const FormItem = Form.Item;

class ApprovalP extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      processInfo: undefined, // 流程相关信息
      currentUser: localStorage.getItem('antd-pro-userId'), // 当前登录用户信息
      inLineEdit: false, // 标记inLine模式下，是否为编辑状态
      timeStamp: new Date().getTime(), // 时间戳，触发组件重新加载数据
    };
  }

  config = config.config;
  // 初始化页面
  init = () => {
    // 获取从其他页面跳转过来的流程信息（代办页面和流程管理页面）
    let processInfo = JSON.parse(sessionStorage.getItem('process'));
    if (processInfo == undefined) return;

    // 将从sessionStorage中获取的信息与const中配置的信息合并
    let find = this.config.filter((item) => item.type == processInfo.type);
    if (find && find.length > 0) {
      processInfo = { ...processInfo, ...find[0] };
    }
    this.setState(
      {
        processInfo: processInfo,
        timeStamp: new Date().getTime(),
      },
      () => {
        // 清空审批意见
        this.props.form.resetFields();
      },
    );

    // 从sessionStorage中删除信息
    sessionStorage.removeItem('process');
  };

  componentDidMount() {
    this.init();
  }

  UNSAFE_componentWillReceiveProps() {
    this.init();
  }

  // 调用接口，设置通过/拒绝/提交
  // Y - 通过、提交
  // N - 拒绝
  setApprovalResult = (e) => {
    const {
      dispatch,
      form: { getFieldValue },
    } = this.props;
    // // 获取审批意见
    const comments = getFieldValue('comments') ? getFieldValue('comments') : '';
    const args = {
      taskId: this.state.processInfo.taskId, // 任务ID（流程中的ID）
      result: e, // 审批结果
      comment: comments, // 审批意见
    };
    dispatch({
      type: 'agencyTaskM/agreeOrNo',
      payload: args,
      callback: (res) => {
        if (res) {
          // 操作成功，关闭当前页面
          dispatch({
            type: 'tabController/closeTab',
            payload: {
              newUrl: '/taskInfoList',
            },
          });
        }
      },
    });
  };

  // 弹出框模式下，点击“确定”，成功后相应事件
  onOk = () => {
    // 重新加载数据
    this.setState({ timeStamp: new Date().getTime() });
  };

  // 编辑按钮(inLine模式)
  onEdit = () => {
    // 修改状态
    this.setState({ inLineEdit: true });
  };

  // inLine模式下，点击了“确定”按钮
  inLineOK = () => {
    this.setState({
      inLineEdit: false, // 修改状态
      timeStamp: new Date().getTime(), // 重新加载数据
    });
  };

  // inLine模式下，点击了“取消”按钮
  inLineCancle = () => {
    // 修改状态
    this.setState({ inLineEdit: false });
  };

  render() {
    const { processInfo, inLineEdit, timeStamp } = this.state;
    const {
      agencyTaskM: { hisData },
      form: { getFieldDecorator },
      loading,
    } = this.props;
    return (
      <div>
        {processInfo == undefined ? (
          <NoQueryC />
        ) : (
          <div>
            <div style={{ display: processInfo.needTitle ? 'show' : 'none', marginBottom: '10px' }}>
              <FirstHeaderC title={processInfo.title} />
            </div>
            {
              // 添加timeStamp，确保每次进来数据都重新刷新
              inLineEdit
                ? processInfo.edit({ businessKey: processInfo.businessKey, onOk: () => this.inLineOK(), onCancle: () => this.inLineCancle() })
                : processInfo.detail({ businessKey: processInfo.businessKey, timeStamp: timeStamp })
            }
            <div style={{ marginTop: '20px', marginBottom: '10px' }}>
              <FirstHeaderC title='审批历史' />
            </div>
            <ApprovalHistory processInstanceId={this.state.processInfo.processInstanceId} />
            <div style={{ display: processInfo.noOperate ? 'none' : 'block' }}>
              <div style={{ marginTop: '20px', marginBottom: '10px' }}>
                <FirstHeaderC title='审批意见' />
              </div>
              <Form>
                <FormItem label=''>{getFieldDecorator('comments', {})(<TextArea placeholder='请输入审批意见' style={{ height: '55px' }} />)}</FormItem>
              </Form>
            </div>
            <div style={{ float: 'right', marginTop: '10px', display: processInfo.noOperate ? 'none' : 'block' }}>
              {/* 当前登录用户为该流程的发起人，且该节点为发起节点时允许编辑 */}
              {this.state.currentUser == processInfo.starter && processInfo.starterNode == true ? (
                <div style={{ display: 'flex' }}>
                  {processInfo.editLayout == 'popUp' && processInfo.edit({ businessKey: processInfo.businessKey, title: '编辑', onOk: () => this.onOk() })}
                  {processInfo.editLayout == 'inLine' && <PrimaryC title='编辑' onClick={() => this.onEdit()} />}
                  <PrimaryC title='提交' onClick={() => this.setApprovalResult('Y')} style={{ marginLeft: '10px' }} />
                </div>
              ) : (
                <div>
                  <PrimaryC title='拒绝' onClick={() => this.setApprovalResult('N')} style={{ marginRight: '10px' }} />
                  <PrimaryC title='通过' onClick={() => this.setApprovalResult('Y')} />
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    );
  }
}
export default connect(({ agencyTaskM, tabController, loading }) => ({ agencyTaskM, tabController, loading }))(Form.create()(ApprovalP));
